package com.easthome.service.impl;


import com.easthome.constant.RedisConstant;
import com.easthome.entity.PageResult;
import com.easthome.entity.QueryPageBean;
import com.easthome.mapper.SetMealMapper;
import com.easthome.pojo.SetMeal;
import com.easthome.service.SetMealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;

@Service
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private JedisPool jedisPool ;

    /**
     * 添加套餐
     * @param checkGroupIds
     * @param setMeal
     */
    @Transactional
    @Override
    public void addSetMeal(Integer[] checkGroupIds, SetMeal setMeal) {
        //将文件名的头删除掉 保留文件名
        String img = setMeal.getImg();
        String[] split = img.split("/");
        setMeal.setImg(split[split.length - 1]);
        setMealMapper.addSetMeal(setMeal);
        addSetMealAndCheckGroup(checkGroupIds, setMeal);
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setMeal.getImg());
        jedis.close();
    }

    /**
     * 分页查询
     */
    @Override
    public PageResult querySetMealPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<SetMeal> page = setMealMapper.querySetMealPage(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getResult());
        return pageResult;
    }

    /**
     * 添加套餐和检查组的关系
     * @param checkGroupIds
     * @param setMeal
     */
    private void addSetMealAndCheckGroup(Integer[] checkGroupIds, SetMeal setMeal) {
        //获取套餐id
        Integer id = setMeal.getId();
        HashMap<Object, Object> map = new HashMap<>();
        for (Integer checkGroupId : checkGroupIds) {
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkGroupId);
            setMealMapper.addSetMealAndCheckGroup(map);
        }
    }
}
